package ua.kharkov.khpi.tarasenko.bach.web.command.common;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserBean;
import ua.kharkov.khpi.tarasenko.bach.core.user.UserSettingsBean;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDAO;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to show settings view.
 * 
 * @author oleksandr
 * 
 */
public class ShowSettingsCommand extends Command {
	private static final Logger log = Logger
			.getLogger(ShowSettingsCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.PAGE_SETTINGS;
		String errorMessage = null;

		HttpSession session = request.getSession();
		Object userBeanObject = session
				.getAttribute(Constant.ATTRIBUTE_USER_BEAN);

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		// User who don't have userBean in it's session is not eligible to
		// access this command, so if userBean is null, there is mistake in the
		// code.
		if (userBeanObject == null) {
			errorMessage = LRManager.getMessage("error_message.not_loged_in");
		} else {
			UserBean userBean = (UserBean) userBeanObject;

			int userId = userBean.getUserId();
			if (log.isTraceEnabled()) {
				log.trace("User with id = " + userId
						+ " requested settings view");
			}

			Connection conn = null;
			try {
				conn = ConnectionManager.getConnection();
				UserDAO userDAO = DAOFactory.getDAOFactory(
						DAOFactory.DAO_TYPE.MYSQL).getUserDAO(conn);
				UserDTO userDTO = userDAO.findUserById(userId);

				// If in session is UserBean with invalid id we have to
				// invalidate session.
				if (userDTO == null) {
					session.invalidate();
					errorMessage = LRManager.getMessage("error_message.perm_denied");
				} else {
					UserSettingsBean bean = createUserSettingsBean(userDTO);

					request.setAttribute(Constant.ATTRIBUTE_USER_SETTINGS_BEAN,
							bean);
					if (log.isTraceEnabled()) {
						log.trace("Set request attribute "
								+ Constant.ATTRIBUTE_USER_SETTINGS_BEAN + "\n"
								+ bean);
					}
				}
			} catch (EShopException e) {
				DBUtils.rollBackAndClose(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}

	/**
	 * Creates UserSettingsBean from UserDTO object.
	 * 
	 * @param userDTO
	 *            .
	 * @return created UserSettingsBean
	 */
	private UserSettingsBean createUserSettingsBean(UserDTO userDTO) {
		UserSettingsBean bean = new UserSettingsBean();
		bean.setId(userDTO.getId());
		bean.setFirstName(userDTO.getFirstName());
		bean.setLastName(userDTO.getLastName());
		bean.setPhone(userDTO.getPhone());
		return bean;

	}
}
